package com.flybutter.usagelab.ui.notifications

import android.app.usage.NetworkStats
import android.app.usage.NetworkStatsManager
import android.content.Context
import android.net.ConnectivityManager
import com.flybutter.usagelab.ui.notifications.NotificationsViewModel
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.telecom.TelecomManager
import android.telephony.TelephonyManager
import android.view.View
import androidx.lifecycle.ViewModelProvider
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.flybutter.usagelab.databinding.FragmentNotificationsBinding

class NetworkFragment : Fragment() {
    private var notificationsViewModel: NotificationsViewModel? = null
    private var binding: FragmentNotificationsBinding? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        notificationsViewModel = ViewModelProvider(this).get(
            NotificationsViewModel::class.java
        )
        binding = FragmentNotificationsBinding.inflate(inflater, container, false)
        val root: View = binding!!.root
        val textView = binding!!.textNotifications
        notificationsViewModel!!.text.observe(viewLifecycleOwner, { s -> textView.text = s })
        renderList(0,System.currentTimeMillis() )
        return root
    }

    fun renderList(startTime: Long,endTime: Long){
        val nm = requireActivity().getSystemService(Context.NETWORK_STATS_SERVICE)
                as NetworkStatsManager
        val usage = nm.querySummary(ConnectivityManager.TYPE_WIFI,null,startTime,endTime)
        val bucket = NetworkStats.Bucket()
        while (usage.hasNextBucket()){
            usage.getNextBucket(bucket);
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }
}